import React, { Component, memo, createRef } from 'react'
import { Link } from 'react-router-dom';
import { History } from 'history';
import { connect } from 'react-redux';
import { bindAll, debounce } from 'lodash'
import { Store } from '../../reducers/types';
import './style.less'
import logo from '../../assets/logo.png'
type Props = {
  history: History,
  Store: Store
}

type States = {
  nav: string,
  scrollY: number
}

class Menu extends Component<any, States> {
  myref: React.RefObject<HTMLElement>;
  onchangenav: (oldscrollY: number) => void;
  constructor(props: Props) {
    super(props)
    console.log(props)
    bindAll(this, ['onscroll', 'onresize'])
    this.onchangenav = debounce(this.changenav, 500)
    this.state = {
      nav: '',
      scrollY: window.scrollY
    }
    this.myref = createRef()
  }

  // 组件挂载后
  componentDidMount() {
    document.addEventListener('scroll', this.onscroll)
    document.addEventListener('resize', this.onresize)
  }

  onscroll(e: Event) {
    const { scrollY } = window
    this.setState({
      scrollY: scrollY
    })
  }

  // 更新后
  componentDidUpdate(prevProps: Props, prevState: States, snapshot: any) {
    const scrollY = prevState.scrollY
    this.changenav(scrollY)
  }

  onresize(e: Event) {
    console.log(e)
  }

  changenav(oldscrollY: number) {
    const { innerHeight, scrollY } = window
    const d = document.querySelector('#nav')
    const nav = this.myref.current?.className
    if (scrollY > innerHeight && oldscrollY > scrollY) {
      if (nav !== 'show') {
        if (d) {
          d.className = 'show'
        }
      }
    } else {
      if (nav === 'show') {
        if (d) {
          d.className = ''
        }
      }
    }
  }

  componentWillUnmount() {
    document.removeEventListener('scroll', this.onscroll)
    document.removeEventListener('resize', this.onresize)
  }

  render() {
    return <nav id="nav" ref={this.myref} >
      <div className="nav-content" >
        <img className="logo" width="150" src={logo} alt="" />
        <div className="nav-content-links" >
          <a target="_blank" rel="noopener noreferrer" href="https://www.hterobot.com">首页</a>
          <a target="_blank" rel="noopener noreferrer" href="https://www.hterobot.com/course">卓越选择</a>
          <a target="_blank" rel="noopener noreferrer" href="https://www.hterobot.com/about">了解我们</a>
          <a target="_blank" rel="noopener noreferrer" href="https://www.hterobot.com/Campus">教育服务</a>
          <a target="_blank" rel="noopener noreferrer" href="https://www.hterobot.com/point">预约试听</a>
          <Link to="/">更多</Link>
          <a target="_blank" rel="noopener noreferrer" href="https://www.hterobot.com/home.html" className="btn btn-warning rounded-pill"> &nbsp; &nbsp; 登 &nbsp; 录 &nbsp; &nbsp; </a>
        </div>
      </div>
    </nav>
  }
}

const mapStateToProps = () => ({})

const mapDispatchToProps = () => ({});


export default connect(mapStateToProps, mapDispatchToProps)(memo(Menu))
